package com.stox.ui.javafx.list.widget;

import java.util.ArrayList;
import java.util.List;

import javafx.collections.ObservableList;
import javafx.scene.control.TreeItem;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.stox.client.ScripClient;
import com.stox.dto.AbstractModel;
import com.stox.dto.Scrip;
import com.stox.dto.WatchList;
import com.stox.ui.javafx.list.client.WatchListClient;

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class WatchListTreeItem extends TreeItem<AbstractModel>{

	@Autowired
	private WatchListClient watchListClient;
	
	@Autowired
	private ApplicationContext applicationContext;
	
	@Autowired
	private ScripClient scripClient;
	
	@Override
	public boolean isLeaf() {
		return getChildren().isEmpty();
	}
	
	private List<TreeItem<AbstractModel>> loadChildren(){
		List<TreeItem<AbstractModel>> children = new ArrayList<>();
		List<WatchList> watchLists = watchListClient.findByParentId(getValue().getId());
		for(WatchList watchList : watchLists){
			WatchListTreeItem treeItem = applicationContext.getBean(WatchListTreeItem.class);
			treeItem.setValue(watchList);
			children.add(treeItem);
		}
		
		List<Scrip> entries = watchListClient.findEntriesByWatchListId(getValue().getId());
		for(AbstractModel watchListEntry : entries){
			children.add(new TreeItem<AbstractModel>(watchListEntry));
		}
		return children;
	}
	
	boolean childrenLoaded = false;
	@Override
	public synchronized ObservableList<TreeItem<AbstractModel>> getChildren() {
		if(childrenLoaded) return super.getChildren();
		childrenLoaded = true;
		super.getChildren().addAll(loadChildren());
		return super.getChildren();
	}
	
}
